from fastapi import APIRouter, Header
from DataModels.database import User, Sync

from DataModels.share import (
    RespInfo,
    RespResultCode,
    StatusInfo,
    TokenPayload,
)
from utils.token import check_token, generate_token


down_router = APIRouter(prefix="/down")


@down_router.post("")
async def down(token=Header(None)):
    ok, info = check_token(token)
    if not ok:
        return info
    tk: TokenPayload = info  # type: ignore
    phone = tk.phone
    user = await User.find_one(User.phone == phone)
    if not user:
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.PhoneNotFound,
                msg="用户不存在",
            )
        )
    sync = await Sync.find_one(Sync.uid == user.uid)
    if not sync:
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.SyncNotFound,
                msg="未找到同步记录",
            )
        )
    return RespInfo(
        status=StatusInfo(
            code=RespResultCode.Success,
            msg="获取成功",
        ),
        token=generate_token(tk),
        list=sync.data,
    )
